<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录</title>
</head>

<body>
<button onclick="login()">登录</button>
<button onclick="test()">test接口调用</button>
<script src="https://cdn.staticfile.net/axios/1.6.5/axios.min.js"></script>
<script src="https://unpkg.com/node-forge@1.3.1/dist/forge.min.js"></script>
<script>
  const tokenKey = 'UA_tks'
  const storage = {
    set(key, value) {
      localStorage.setItem(key, value);
    },
    get(key) {
      return localStorage.getItem(key);
    },
    remove(key) {
      localStorage.removeItem(key);
    }
  }

  async function getPublicKey() {
    let key = storage.get('ua_publicKay')
    if (!key || key === 'undefined') {
      let result = await axios.get('http://127.0.0.1:3000/api/getPublicKey')
      console.log('result: ', result);
      key = result.data.data.publicKey
      console.log('key: ', key);
      key = key.replace(/\. +/g, '')
      key = key.replace(/[\r\n]/g, '')
      storage.set('ua_publicKay', key)
    }
    return key
  }


  // 添加请求拦截器
  axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
  axios.interceptors.response.use(response => {
    console.log('response: ', response);
    // 检查响应头中是否有 'Authorization' 字段
    const authHeader = response.headers['authorization'];
    if (authHeader) {
      // 处理新的授权令牌
      console.log('Authorization header:', authHeader);
      // 例如，你可以在这里更新应用的令牌存储
      storage.set(tokenKey, authHeader);
    }
    return response;
  }, error => {
    // 对响应错误进行处理
    return Promise.reject(error);
  });

  function encrypt(publicKey, value) {
    const publicKeyObj = forge.pki.publicKeyFromPem(publicKey);
    const encrypted = publicKeyObj.encrypt(value, 'RSAES-PKCS1-V1_5');
    console.log(forge.util.encode64(encrypted))
    return forge.util.encode64(encrypted);
  }

  async function login() {
    let key = await getPublicKey()
    let result = await axios.post('http://127.0.0.1:3000/api/login', {username: "admin123", password: encrypt(key, 'th123456')})
    token = result.data.data.token;
    storage.set(tokenKey, token)
    console.log('登陆获取token成功token: ', token);
  }

  async function getToken() {
    let token = storage.get(tokenKey)
    if (!token || token === 'undefined') {
      try {
        let key = await getPublicKey()
        let result = await axios.post('http://127.0.0.1:3000/api/login', {username: "admin123", password: encrypt(key, 'th123456')})
        token = result.data.data.token
        storage.set(tokenKey, token)
        return token
      } catch (err) {
        console.error(err)
      }
    }
    console.log('本地存储成功的token: ', token);
    return token
  }


  async function test() {
    let token = await getToken()
    console.log('token！！！: ', `Bearer ${token}`);
    let result = await axios.post('http://127.0.0.1:3000/api/test', {}, {
      headers: {
        "Authorization": `Bearer ${token}`
      },
    })
    console.log(result)
  }


</script>
</body>

</html>